
#region Imported Namespaces
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text.RegularExpressions;
#endregion

namespace PHSRAG.Utility
{
	/// <summary>
	/// The InstanceCreator class create an instance of a type using reflection.
	/// </summary>
	public class InstanceCreator
	{
		/// <summary>
		/// Create an instance of the specified type.
		/// </summary>
		/// <param name="assemblyName">Fully qualified name of the assembly defining the type</param>
		/// <param name="className">Name of the class defining the type</param>
		/// <param name="args">Parameters (if any) for the class constructor</param>
		/// <returns>Reference to an object of the appropriate type</returns>
		public static object Create(string assemblyName, string className, params object[] args)
		{
			object instance = null;
			try
			{
				if (assemblyName == null)
					throw new Exception("Assembly name cannot be null");
				if (className == null)
					throw new Exception("Class name cannot be null");

				string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); 
				Match m = (new Regex(@"file:\\(?<path>.+)")).Match(path);
				if (!m.Success)
					throw new Exception("Failed to get assembly path");

				path = m.Groups["path"].Value;
				FileInfo fi = new FileInfo(string.Format("{0}.dll", Path.Combine(path, assemblyName)));
				if (!fi.Exists)
					throw new Exception("No Assembly/Class at " + fi.FullName);

				ObjectHandle h = Activator.CreateInstance(assemblyName, assemblyName + "." + className, true,
					BindingFlags.Instance | BindingFlags.Public, null, args, null, null, null);
				instance = h.Unwrap();
			}
			catch (Exception e)
			{
				ExceptionReport.WriteToEventLog("InstanceCreator", e, true, ExceptionReport.ReportType.Error);
				throw;
			}
			return instance;
		}
	}
}

// --- EOF ---
